//
//  MainViewController.m
//  us
//
//  Created by lhx on 2025/4/2.
//

#import "MainViewController.h"
#import "MatchViewController.h"
#import "MatchTipsView.h"
#import "USChatKit.h"
#import "USMainHeaderView.h"
#import "CharacterView.h"
#import "USLoveCompassViewController.h"
#import "USLoveCompassGuideController.h"
#import "USDayAskView.h"
#import "DTAlertTextFieldView.h"
#import "USShareUsViewController.h"
#import "CharacterViewController.h"
#import "USMainHomeToolBar.h"
#import "USMemorialDayController.h"
#import "USAskListViewController.h"
#import "USAskDetailViewController.h"
#import "USMomentsController.h"
#import "TearOpenView.h"
#import "USTodayTalkView.h"
#import <WXSTransition/UINavigationController+WXSTransition.h>
#import "USRealtimeLocationManager.h"
#import "USOurListController.h"
#import "USTodayTarotController.h"
#import "USTarotCardDetailController.h"
#import "USNoticeViewController.h"
#import "USTodayViewController.h"
#import "USMemorialDayModel.h"
#import "USTalkModel.h"
#import "USImageActivityItem.h"
#import "USTarotModel.h"
#import "USTarotCard.h"

@interface MainViewController ()<EMChatManagerDelegate>

@property (nonatomic, strong) MatchTipsView *tipsView;

@property (nonatomic, strong) UIImageView *sexImageView;

@property (nonatomic) NSInteger homeLogoIndex;

@property (nonatomic, strong) UIView *msgTagView;

@property (nonatomic,strong) UIButton *rightBubbleBtn;
@property (nonatomic,strong) UIButton *leftBubbleBtn;

@property (nonatomic,strong) CharacterView *leftCharacterView;

@property (nonatomic,strong) CharacterView *rightCharacterView;

@property (nonatomic,strong) USMainHeaderView *headerView;

@property (nonatomic,strong) USMainHomeToolBar *homeToolBar;

@property (nonatomic,strong) TearOpenView *tearOpenView;
@property (nonatomic,strong) USTodayTalkView *todayTalkView;
@property (nonatomic,strong) USTalkModel *todayTalkModel;
@property (nonatomic,strong) USTarotModel *tarotModel;
@end

@implementation MainViewController


- (void)setupChat{
    
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
    
}

#pragma mark - EMChatManagerDelegate

- (void)cmdMessagesDidReceive:(NSArray<EMChatMessage *> *)aCmdMessages {
    for (EMChatMessage *msg in aCmdMessages) {
        if (![msg.body isKindOfClass:[EMCmdMessageBody class]]) continue;
        
        if (msg.direction == EMMessageDirectionSend) {
            return;
        }
        
        EMCmdMessageBody *body = (EMCmdMessageBody *)msg.body;
        NSString *action = body.action;
        
        NSLog(@"📩 收到CMD消息：%@ from: %@", action, msg.from);
        
        if ([action isEqualToString:@"appear_compass"]) {
            // 对方打开指南针界面，开始上传位置
            [[USRealtimeLocationManager shared] startDispatchingWithInterval:10.0];
        } else if ([action isEqualToString:@"disappear_compass"]) {
            // 对方退出指南针界面，10分钟上传一次 
            [[USRealtimeLocationManager shared] startDispatchingWithInterval:60.f * 10];
            
        }else if ([action isEqualToString:@"realtime_location"]){
            
            NSLog(@"📍收到位置 - %@",msg.ext);
            [[USRealtimeLocationManager shared]saveRelUserLocationInfo:msg.ext];
            [[NSNotificationCenter defaultCenter]postNotificationName:USNotificationRelUserLocationChange object:nil];
            
        }else if ([action isEqualToString:USIMCmdAction_UploadUserInfo]){
            NSLog(@"更新用户信息");
            [self getUserInfo];
        }else if ([action isEqualToString:USIMCmdAction_GetTalk]){
            NSLog(@"领取问答");
            [self getTodayTalkState];
        }else if ([action isEqualToString:USIMCmdAction_UnMatch]){
            NSLog(@"解除匹配");
            [self getUserInfo];
            //删除本地所以环信消息
            [[[EMClient sharedClient].chatManager getConversationWithConvId:USUser.user.relImUserName] deleteAllMessages:nil];
            
        }else if ([action isEqualToString:USIMCmdAction_TalkNotic]){
            NSLog(@"问答提醒");
            
        }else if ([action isEqualToString:USIMCmdAction_TarotNotic]){
            NSLog(@"塔罗牌提醒");
            
        }
    }
}

- (void)messagesDidReceive:(NSArray<EMChatMessage *> *)aMessages {

}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupView];
    [self setupChat];
    
    [self getTodayTarot];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appWillEnterForeground)
                                                 name:UIApplicationWillEnterForegroundNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getUserInfo) name:USNotificationMatch object:nil];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
 
    self.navigationController.navigationBar.prefersLargeTitles = NO;
    [self getUserInfo];
    [self getNoticeList];
    if (USUser.user.sex == 0) {
        self.sexImageView.image = [UIImage imageNamed:@"img_home_date_tag_red"];
    }else {
        self.sexImageView.image = [UIImage imageNamed:@"img_home_date_tag"];
    }
}

//app从前台唤醒
- (void)appWillEnterForeground{
    
    [self updateLocationIfNeed];
    
}

///当用户开启指南针功能，并且有匹配用户开启
- (void)updateLocationIfNeed{
    
    if (![[NSUserDefaults standardUserDefaults]boolForKey:USKeyHaveOpenLoveCompass]) {
        return;
    }
    
    if (USUser.user.relType != 1) {
        return;
    }
    
    //十分钟传一次
    [[USRealtimeLocationManager shared]startDispatchingWithInterval:60 * 10];
    
}

- (void)getUserInfo {
   
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (USUser.user.relStatus == 1) {
        [params setValue:USUser.user.relUserId forKey:@"relUserId"];
    }
    [[EMNetWork shareManager]em_post:API_BothPartiesInfo params:params hud:nil showError:YES success:^(EMApiModel *api) {
        if (api.success == NO) {
            return;
        }
        
        [self.view endEditing:YES];

        if (![api.data isKindOfClass:[NSDictionary class]]) {
            return;
        }
        
        NSDictionary *dict = (NSDictionary *)api.data;
        
        if (![dict.allKeys containsObject:@"myUser"]) {
            return;
        }
        
        NSString *token = USUser.user.token?:@"";
        USUser *user = [USUser mj_objectWithKeyValues:dict[@"myUser"]];
        if ([dict.allKeys containsObject:@"relUser"]) {
            USUser *relUser = [USUser mj_objectWithKeyValues:dict[@"relUser"]];
            user.relUser = relUser;
        }
        if (user.relStatus == 1) {
            self.tipsView.hidden = YES;
        }else{
            self.tipsView.hidden = NO;
        }
        self.homeToolBar.hidden = user.relStatus == 0;

        if (user.token.length == 0) {
            user.token = token;
        }
        [USUser saveUser:user];
        
        [[USUser user]clearCharacter];
        
        [self reloadUserInfoUI];
        
        [self updateLocationIfNeed];
        
        [self homeMemorialDay];

        [self getTodayTalkState];

    } fail:^{
        
    }];
    
}

- (void)updateSayToRel:(NSString *)say{
    [USFeedbackTool notifySuccess];

    NSDictionary *params = @{
        @"sayToRel" : say,
    };

    [[EMNetWork shareManager] em_post:API_SayToRel
                               params:params
                                  hud:nil
                           showError:YES
                              success:^(EMApiModel *api) {
        [self.view endEditing:YES];
        
        if (!api.success) {
            return;
        }
 
        USUser *user = [USUser user];
        user.sayToRel = say?:@"";
        [USUser saveUser:user];
        [self reloadUserInfoUI];
        
        [USIMCmdCustomManager imSendCmdWithAction:USIMCmdAction_UploadUserInfo andExt:@{}];

    } fail:^{
                
    }];
}

///纪念日首页
- (void)homeMemorialDay{
    [[EMNetWork shareManager] em_post:API_AnniversaryHome
                               params:@{@"sharedSpaceId":USUser.user.sharedSpaceId?:@""}
                                  hud:nil
                            showError:NO
                              success:^(EMApiModel *api) {
 
        USMemorialDayModel *homeDayModel = [USMemorialDayModel mj_objectWithKeyValues:api.data[@"anniversary"]];

        self.headerView.hidden = USUser.user.relStatus == 0;
        
        self.headerView.dayLab.hidden = NO;
        self.headerView.titleLab.hidden = NO;
        self.headerView.todayLab.hidden = YES;

        NSInteger count = labs(homeDayModel.dayCount);
        if (homeDayModel) {
            
        
            if (homeDayModel.togetherFlag) {
                [self.headerView setDefaultInfoWithName0:USUser.user.nickname
                                                   name1:USUser.user.relUser.nickname
                                         anniversaryName:homeDayModel.anniversaryName];

                if (homeDayModel.dayCount == 0 && homeDayModel.includeStart) {
                    count = 1;//在一起今天且算起始日
                    [self.headerView setDay:count color:[UIColor jk_colorWithHexString:homeDayModel.color]];
                }else if(homeDayModel.dayCount == 0 && (homeDayModel.repeatYearly || homeDayModel.togetherFlag)){
                    //今天
                    self.headerView.dayLab.hidden = YES;
                    self.headerView.titleLab.hidden = YES;
                    self.headerView.todayLab.hidden = NO;
                    self.headerView.todayLab.textColor = [UIColor jk_colorWithHexString:homeDayModel.color];

                }else {
                    [self.headerView setDay:count color:[UIColor jk_colorWithHexString:homeDayModel.color]];
                }

            }else{
                
                if (homeDayModel.dayCount < 0) {
                    [self.headerView setOtherInfoWithName:homeDayModel.anniversaryName];
                    [self.headerView setDay:count color:[UIColor jk_colorWithHexString:homeDayModel.color]];

                }else if (homeDayModel.dayCount == 0 && (homeDayModel.repeatYearly || homeDayModel.togetherFlag)){
                    //今天
                    self.headerView.dayLab.hidden = YES;
                    self.headerView.titleLab.hidden = YES;
                    [self.headerView setOtherInfoWithName:homeDayModel.anniversaryName];
                    self.headerView.todayLab.hidden = NO;
                    self.headerView.todayLab.textColor = [UIColor jk_colorWithHexString:homeDayModel.color];

                }else{
                    [self.headerView setOtherInfoWithName:[NSString stringWithFormat:@"%@\n还有",homeDayModel.anniversaryName]];
                    [self.headerView setDay:count color:[UIColor jk_colorWithHexString:homeDayModel.color]];
                }

            }

             
        }else{
            [self.headerView setDay:USUser.user.metTimeDescription];
            [self.headerView setDefaultInfoWithName0:USUser.user.nickname name1:USUser.user.relUser.nickname anniversaryName:@""];
        }
        
  
    } fail:^{
        
        
    }];
}

///今日问答领取状态
- (void)getTodayTalkState {
    @weakify(self)
    [[EMNetWork shareManager] em_post:API_DailyTalkToday
                               params:nil
                                  hud:nil
                            showError:NO
                              success:^(EMApiModel *api) {
        @strongify(self)
        if (!api.success) {
            self.tearOpenView.hidden = YES;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.homeToolBar mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.left.mas_offset(0);
                    make.right.mas_offset(0);
                    make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom).mas_offset(-16);
                    make.height.mas_equalTo(40);
                }];
                
                [self.view layoutIfNeeded];
            });
  
            return;
        }
        USTalkModel *model = [USTalkModel mj_objectWithKeyValues:api.data];
        self.todayTalkModel = model;
        self.tearOpenView.contentLab.text = model.talkTitle;
        NSLog(@"USUser.user.relStatus = %li",USUser.user.relStatus);
        if (model.talkState) {
            USTalkModel *taskModel = [USTalkModel mj_objectWithKeyValues:api.data[@"dailyTalk"]];
            taskModel.talkState = 1;
            self.todayTalkModel = taskModel;//已经领取，重新赋值
            if (model.completionStatus == 1) {
              //已完成不需要显示
                self.tearOpenView.hidden = YES;
                self.todayTalkView.hidden = YES;
            }else{
                self.tearOpenView.hidden = YES;
                self.todayTalkView.hidden = USUser.user.relStatus == 0;
                self.todayTalkView.contentLab.text = model.talkTitle;
            }
        }else {
            self.tearOpenView.hidden = USUser.user.relStatus == 0;
            self.todayTalkView.hidden = YES;
        }
        
     
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.homeToolBar mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_offset(0);
                make.right.mas_offset(0);
                if (model.completionStatus == 1) {
                    make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom).mas_offset(-16);
                }else{
                    make.bottom.mas_equalTo(self.tearOpenView.mas_top).mas_offset(-12);
                }
                make.height.mas_equalTo(40);
            }];
            [self.view layoutIfNeeded];
        });
    } fail:^{
        
        
    }];
}

- (void)getTodayTalk {
    [[EMNetWork shareManager] em_post:API_DailyTalkGetToday
                               params:@{@"sysDailyTalkId":self.todayTalkModel.sysDailyTalkId?:@""}
                                  hud:nil
                            showError:NO
                              success:^(EMApiModel *api) {
 
        if (!api.success) {
            return;
        }
        USTalkModel *model = [USTalkModel mj_objectWithKeyValues:api.data[@"dailyTalk"]];
        self.todayTalkModel = model;
        self.tearOpenView.contentLab.text = model.talkTitle;
        
        [USIMCmdCustomManager imSendCmdWithAction:USIMCmdAction_GetTalk andExt:@{}];

    } fail:^{
        
        
    }];
}

///今日塔罗牌
- (void)getTodayTarot {
    [[EMNetWork shareManager] em_post:TarotToday
                               params:nil
                                  hud:nil
                            showError:NO
                              success:^(EMApiModel *api) {
 
        if (!api.success) {
            return;
        }
        USTarotModel *model = [USTarotModel mj_objectWithKeyValues:api.data[@"totalTarot"]];
        self.tarotModel = model;
        
        
        self.homeToolBar.items = [self homeItems];
 
    
    } fail:^{
        
        
    }];
}
- (void)getNoticeList{
    NSDictionary *params = @{
                              @"readType":@(0)
    };
    
    [[EMNetWork shareManager] em_post:NoticeList
                               params:params
                                  hud:nil
                            showError:YES
                              success:^(EMApiModel *api) {
        
        if (!api.success) {
            return;
        }
        
        if (api.data[@"noticeList"][@"total"]) {
            NSInteger total = [api.data[@"noticeList"][@"total"] intValue];
            self.msgTagView.hidden = total > 0 ? NO : YES;
        }
                
    } fail:^{
        
        
    }];

}
- (void)setupView {

    self.tipsView = [MatchTipsView jk_loadInstanceFromNib];
    self.tipsView.hidden = YES;
    [self.view addSubview:self.tipsView];
    [self.tipsView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_safeAreaLayoutGuideLeft).mas_offset(20);
        make.right.mas_equalTo(self.view.mas_safeAreaLayoutGuideRight).mas_offset(-20);
        make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom).mas_offset(-4);
    }];

    @weakify(self);
    [self.tipsView jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        @strongify(self);
        MatchViewController *vc = [[MatchViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }];

    UIButton *msgButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [msgButton setImage:[UIImage imageNamed:@"icon_msg"] forState:UIControlStateNormal];
    [msgButton addTarget:self action:@selector(msgAction:) forControlEvents:UIControlEventTouchUpInside];

    self.msgTagView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 9, 9)];
    self.msgTagView.layer.cornerRadius = 4.5;
    self.msgTagView.backgroundColor = UIColor.us_redColor;
    self.msgTagView.layer.masksToBounds =YES;
    [msgButton addSubview:self.msgTagView];
    self.msgTagView.hidden = YES;
    [self.msgTagView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(msgButton.mas_right);
        make.top.mas_equalTo(msgButton.mas_top);
        make.width.height.mas_equalTo(9);
    }];
    
    UIBarButtonItem *msgItem = [[UIBarButtonItem alloc] initWithCustomView:msgButton];
    UIBarButtonItem *safariItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"set_icon-4"] style:UIBarButtonItemStylePlain target:self action:@selector(compassAction:)];
    self.navigationItem.rightBarButtonItems = @[msgItem,safariItem];
        
    UILabel *titleLab = [UILabel new];
    titleLab.text = @"Today";
    titleLab.font = [UIFont systemFontOfSize:32 weight:UIFontWeightSemibold];
    [titleLab sizeToFit];
    
    UIImageView *imageView = [[UIImageView alloc]init];
    self.sexImageView = imageView;
    if (USUser.user.sex == 0) {
        imageView.image = [UIImage imageNamed:@"img_home_date_tag_red"];
    }else {
        imageView.image = [UIImage imageNamed:@"img_home_date_tag"];
    }
    [titleLab addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.bottom.mas_equalTo(titleLab);
    }];

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] init];
    [titleLab addGestureRecognizer:tapGesture];
    titleLab.userInteractionEnabled = YES;
    [[tapGesture.rac_gestureSignal takeUntil:self.rac_willDeallocSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
        @strongify(self);
        USTodayViewController *vc = [[USTodayViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:titleLab];
    
    
    USMainHeaderView *headerView = [USMainHeaderView jk_loadInstanceFromNib];
    [headerView jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        @strongify(self)
        [USFeedbackTool impactSoft];
        [self pushToMemorialDay];
    }];
    _headerView = headerView;
    [self.view addSubview:headerView];
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop).mas_offset(30);
    }];
    
    UIView *c_contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 140)];
    [self.view addSubview:c_contentView];
    
    [c_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.centerY.mas_equalTo(self.view);
        make.height.mas_equalTo(140);
    }];

    CharacterView *leftCharacterView = [[CharacterView alloc]initWithFrame:CGRectMake(0, 0, 140, 140)
                                                                 character:USUser.user.character];
    _leftCharacterView = leftCharacterView;
    
    CharacterView *rightCharacterView = [[CharacterView alloc]initWithFrame:CGRectMake(0, 0, 140, 140)
                                                                  character:USUser.user.relCharacter];
    _rightCharacterView = rightCharacterView;
    
    [leftCharacterView jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        @strongify(self)
        [USFeedbackTool impactMedium];
        [self leftCharacterAction:gestureRecoginzer.view];
    }];
    
    [c_contentView addSubview:leftCharacterView];
    
    [c_contentView addSubview:rightCharacterView];
    
    UIImageView *shadowImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"Rectangle 236"]];
    [c_contentView addSubview:shadowImageView];
    
    [leftCharacterView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(c_contentView.mas_centerX).mas_offset(10);
        make.top.mas_equalTo(c_contentView);
        make.width.height.mas_equalTo(140);
    }];
    
    [rightCharacterView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(c_contentView.mas_centerX).mas_offset(-10);
        make.top.mas_equalTo(c_contentView);
        make.width.height.mas_equalTo(140);
    }];
    
    [shadowImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.bottom.mas_equalTo(c_contentView);
        make.height.mas_equalTo(20);
    }];
    
    UIButton *recordBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    recordBtn.tintColor = UIColor.blackColor;
    UIButtonConfiguration *config = [UIButtonConfiguration filledButtonConfiguration];
    config.cornerStyle = UIButtonConfigurationCornerStyleCapsule;
    config.title = @"记录现在";
    config.contentInsets = NSDirectionalEdgeInsetsMake(8, 20, 8, 20);
    recordBtn.configuration = config;
    [self.view addSubview:recordBtn];
    [recordBtn addTarget:self action:@selector(recordAction) forControlEvents:UIControlEventTouchUpInside];
    [recordBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(c_contentView.mas_bottom).mas_offset(30);
    }];
    

    // 5️⃣ 加到视图上并设置约束
    [self.view addSubview:self.rightBubbleBtn];
    [self.rightBubbleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_greaterThanOrEqualTo(headerView.mas_bottom);
        make.bottom.mas_equalTo(rightCharacterView.mas_top);
        make.left.mas_equalTo(rightCharacterView.mas_centerX).mas_offset(12);
        make.width.mas_greaterThanOrEqualTo(40);
        make.width.mas_lessThanOrEqualTo(120);
    }];
    
    [self.view addSubview:self.leftBubbleBtn];
    [self.leftBubbleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(leftCharacterView.mas_top);
        make.right.mas_equalTo(leftCharacterView.mas_centerX).mas_offset(-12);
        make.width.mas_greaterThanOrEqualTo(40);
        make.width.mas_lessThanOrEqualTo(120);
    }];
    
    TearOpenView *openView = [[TearOpenView alloc]initWithFrame:CGRectMake(16, 100, self.view.jk_width - 16 * 2, 93)];
    [self.view addSubview:openView];
    self.tearOpenView = openView;
    openView.hidden = YES;
    openView.didReachBottomBlock = ^{
        @strongify(self)
        [self getTodayTalk];
    };
    openView.tearCompletedBlock = ^{
        @strongify(self)
        [self goToAskDetailViewController];
    };
    
    [openView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(16);
        make.right.mas_offset(-16);
        make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom).mas_offset(-16);
        make.height.mas_equalTo(93);
    }];
    
    
    USTodayTalkView *talkView = [[USTodayTalkView alloc]initWithFrame:CGRectMake(16, 100, self.view.jk_width - 16 * 2, 93)];
    [self.view addSubview:talkView];
    self.todayTalkView = talkView;
    talkView.hidden = YES;
    talkView.clickTodayTalkBlock = ^{
        @strongify(self)
        [self goToAskDetailViewController];
    };
    
    [talkView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(16);
        make.right.mas_offset(-16);
        make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom).mas_offset(-16);
        make.height.mas_equalTo(93);
    }];

    self.homeToolBar = [[USMainHomeToolBar alloc]initWithFrame:CGRectMake(0, 0, self.view.jk_width, 40) items:[self homeItems]];
    self.homeToolBar.hidden = USUser.user.relStatus == 0;
    [self.view addSubview:self.homeToolBar];
    [self.homeToolBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(0);
        make.right.mas_offset(0);
        make.bottom.mas_equalTo(openView.mas_top).mas_offset(-12);
        make.height.mas_equalTo(40);
    }];
    
    [self reloadUserInfoUI];
    
    

    
}

- (NSArray *)homeItems{
    
    @weakify(self)
    DTItem *item0 = [DTItem itemWithTitle:@"问答" image:[UIImage imageNamed:@"home_icon-2"] tag:0 identifier:nil handle:^(DTItem *item) {
        @strongify(self)
        [self pushToAskList];
    }];
    
    DTItem *item3 = [DTItem itemWithTitle:@"清单" image:[UIImage imageNamed:@"ic_list"] tag:0 identifier:nil handle:^(DTItem *item) {
        @strongify(self)
        [self goToOurListController];
    }];
    
    DTItem *item1 = [DTItem itemWithTitle:@"日记" image:[UIImage imageNamed:@"home_icon-1"] tag:0 identifier:nil handle:^(DTItem *item) {
        @strongify(self)
        [self recordAction];
    }];
    
    DTItem *item2 = [DTItem itemWithTitle:@"纪念日" image:[UIImage imageNamed:@"home_icon"] tag:0 identifier:nil handle:^(DTItem *item) {
        @strongify(self)
        [self pushToMemorialDay];
    }];
    
//    BOOL hasDrawnToday = [[NSCalendar currentCalendar] isDateInToday:USUser.user.lastDrawCardDate];

    //抽了塔罗牌，tag = 0，否则为1，显示小圆点
    NSInteger item4Tag = self.tarotModel.myStatus==YES?0:1;
    
    DTItem *item4 = [DTItem itemWithTitle:@"塔罗运势" image:[UIImage imageNamed:@"ic_tlp"] tag:item4Tag identifier:nil handle:^(DTItem *item) {
        @strongify(self)
        [self taLuoPaiAction];
    }];
    
    return @[item0,item4,item3,item1,item2];
}

- (UIButton *)rightBubbleBtn{
    if (!_rightBubbleBtn) {
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        _rightBubbleBtn = btn;
        // 1️⃣ 创建 configuration
        UIButtonConfiguration *btConfig = [UIButtonConfiguration plainButtonConfiguration];
        btConfig.title = USUser.user.relUser.sayToRel;
        btConfig.baseForegroundColor = UIColor.labelColor;
        btConfig.contentInsets =  NSDirectionalEdgeInsetsMake(4, 6, 12, 6);

        // 3️⃣ 设置背景图
        UIImage *bubble = [[UIImage imageNamed:@"img_bubble"] resizableImageWithCapInsets:UIEdgeInsetsMake(15, 30, 20, 15)];
        btConfig.background.image = bubble;
        btn.configuration = btConfig;
        
        btn.titleLabel.adjustsFontSizeToFitWidth = YES;

    }
    return _rightBubbleBtn;
    
    
}

- (UIButton *)leftBubbleBtn{
    
    if (!_leftBubbleBtn) {
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        _leftBubbleBtn = btn;
        // 1️⃣ 创建 configuration
        UIButtonConfiguration *btConfig = [UIButtonConfiguration plainButtonConfiguration];
        btConfig.title = USUser.user.sayToRel;
        btConfig.baseForegroundColor = UIColor.labelColor;
        btConfig.contentInsets =  NSDirectionalEdgeInsetsMake(4, 6, 12, 6);
        // 3️⃣ 设置背景图
        UIImage *bubble = [[UIImage imageNamed:@"img_bubble2"] resizableImageWithCapInsets:UIEdgeInsetsMake(15, 15, 20, 30)];
        btConfig.background.image = bubble;
        btn.configuration = btConfig;
    }
    return _leftBubbleBtn;
    
}


- (void)leftCharacterAction:(UIView *)sender{
    
    @weakify(self)
    DTItem *takePhoto = [DTItem itemWithTitle:@"状态" image:[UIImage imageNamed:@"icon"] tag:0 identifier:nil handle:^(DTItem *item) {
        @strongify(self)
        [self prepareSetStatuAction];
    }];
    
    DTItem *choosePhoto = [DTItem itemWithTitle:@"换装" image:[UIImage imageNamed:@"icon-1 1"] tag:0 identifier:nil handle:^(DTItem *item) {
        @strongify(self)
        [self setupCharacterAction];
    }];
    DTItem *share = [DTItem itemWithTitle:@"分享形象" image:[UIImage imageNamed:@"icon-2 1"] tag:0 identifier:nil handle:^(DTItem *item) {
        @strongify(self)
        [self shareCharacterAction];
    }];
    
    DTTargetView *targetView = [[DTTargetView alloc]initWithTargetView:sender item:@[takePhoto,choosePhoto,share] noDismissDuration:YES];
    [targetView show];

}

#pragma mark - aciton;

- (void)msgAction:(id)sender{
    
    USNoticeViewController *vc = [USNoticeViewController new];
    [self.navigationController pushViewController:vc animated:YES];
   
}

- (void)compassAction:(id)sender{
    [USFeedbackTool impactSoft];

    if (USUser.user.relStatus == 0) {
        MatchViewController *vc = [[MatchViewController alloc]init];
        [UIViewController.topViewController.navigationController pushViewController:vc animated:YES];
        return;
    }
    if ([[NSUserDefaults standardUserDefaults]boolForKey:USKeyHaveOpenLoveCompass] == YES) {
        
        USLoveCompassViewController *vc = [USLoveCompassViewController new];
        [self.navigationController pushViewController:vc animated:YES];
        return;
        
    }
    
    USLoveCompassGuideController *vc = [USLoveCompassGuideController new];
    @weakify(self)
    vc.didStartBlock = ^{
        @strongify(self)
        [self.navigationController popViewControllerAnimated:YES];
        [[NSUserDefaults standardUserDefaults]setBool:YES forKey:USKeyHaveOpenLoveCompass];
        [self updateLocationIfNeed];
        [self compassAction:nil];
    };
    [self.navigationController pushViewController:vc animated:YES];
    
}


- (void)gotoChat {
    if (USUser.user.relStatus == 1) {
        USChatController *vc = [USChatController new];
        vc.conversationId = USUser.user.relImUserName;
        [self.navigationController pushViewController:vc animated:YES];
        
    }else {
        MatchViewController *vc = [[MatchViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

//设置状态
- (void)prepareSetStatuAction{
    
    DTAlertTextFieldView *tfView = [DTAlertTextFieldView alertContentView];
    tfView.textField.placeholder = @"如：✨想你";
    tfView.textField.jk_maxLength = 25;
    
    MOAlertBaseView *alert = [[MOAlertBaseView alloc]initWithTitle:@"设置下你的状态吧" detailTitle:@"状态只会保存24小时噢" contentView:tfView leftButtonImageName:nil rightButtonImageName:nil autoDissmiss:NO tapDissmiss:YES];
    
    @weakify(self)
    @weakify(alert)
    alert.didClickIndexBlock = ^(NSInteger index) {
        @strongify(self)
        @strongify(alert)
        if (index == 1) {
            [self setupStatus:tfView.textField.text];
            [alert dismss];
        }else{
            [alert dismss];
        }
        
    };
    [alert show];
}

- (void)taLuoPaiAction{
    
    [USFeedbackTool impactSoft];
    
    if (self.tarotModel.myStatus == 1 && self.tarotModel.tarotDetailList.count > 0) {
        USTarotCardDetailController *vc = [[USTarotCardDetailController alloc]init];
        if (self.tarotModel) {
            vc.tarotModel = self.tarotModel;
            
            for (USTarotDetailModel *detailModel in self.tarotModel.tarotDetailList) {
                USTarotCard *card = [USTarotCard new];
                
                card = [[USTarotCard alloc] init];
                card.name = detailModel.tarotTitle;
                card.orientation = detailModel.orientation;
                card.imageName = detailModel.tarotTitle;
                card.answer = detailModel.tarotContent;
                card.date = [NSDate dateWithTimeIntervalSince1970:detailModel.gmtCreate];
                if ([detailModel.userId isEqualToString:USUser.user.userId]) {
                    vc.activeCard = card;
                }else {
                    vc.relActiveCard = card;
                }
            }
           
        }
        [self.navigationController pushViewController:vc animated:YES];
        
    }else {
        USTodayTarotController *vc = [USTodayTarotController new];
        vc.tarotModel = self.tarotModel;
        [self.navigationController pushViewController:vc animated:YES];
        
    }

}

- (void)setupStatus:(NSString *)status{
    
    [self updateSayToRel:status];
    
}

//设置形象
- (void)setupCharacterAction{
    
    CharacterViewController *vc = [CharacterViewController new];
    vc.isEdit = YES;
    [self.navigationController pushViewController:vc animated:YES];

}

//分享形象
- (void)shareCharacterAction{
        
//    UIImage *image = [USUser.user.character snapshotImage];
//    if (!image) return;
//    
//    USImageActivityItem *item = [[USImageActivityItem alloc]initWithImage:image];
//    item.title = @"形象";
//    
//    UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:@[item] applicationActivities:nil];
//    activityVC.popoverPresentationController.sourceView = self.view;
//    [self presentViewController:activityVC animated:YES completion:nil];
    
    
    USShareUsViewController *vc = [USShareUsViewController new];
    DTNavigationController *navc = [[DTNavigationController alloc]initWithRootViewController:vc];
    [self presentViewController:navc animated:YES completion:nil];
    
}
- (void)recordAction {
    if (USUser.user.relStatus == 1) {
        USMomentsController *vc = [[USMomentsController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }else {
        MatchViewController *vc = [[MatchViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
 
}

- (void)pushToAskList{
    
    USAskListViewController *vc = [USAskListViewController new];
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)pushToMemorialDay{
    
    USMemorialDayController *vc = [USMemorialDayController new];
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)goToAskDetailViewController{
    [USFeedbackTool impactSoft];
    
    USAskDetailViewController *vc = [USAskDetailViewController new];
    vc.talkModel = self.todayTalkModel;
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)goToOurListController{
    
    [USFeedbackTool impactSoft];
    USOurListController *vc = [USOurListController new];
    [self.navigationController pushViewController:vc animated:YES];
    
}

//刷新用户信息的UI
- (void)reloadUserInfoUI{
    
    self.leftCharacterView.character = USUser.user.character;
    self.rightCharacterView.character = USUser.user.relCharacter;
    
    if (USUser.user.sayToRel.length > 0) {
        self.leftBubbleBtn.hidden = NO;
        UIButtonConfiguration *config1 = [self.leftBubbleBtn.configuration updatedConfigurationForButton:self.leftBubbleBtn]; // iOS 17+ 推荐用法（自动生成新 config）
  
        config1.attributedTitle = [self bubbleAttributeWithTitle:USUser.user.sayToRel];

        self.leftBubbleBtn.configuration = config1;
        
    }else{
        
        self.leftBubbleBtn.hidden = YES;
    }

    if (USUser.user.relUser.sayToRel.length > 0) {
        
        self.rightBubbleBtn.hidden = NO;
        // 创建一个新的配置（基于旧的）
        UIButtonConfiguration *config = [self.rightBubbleBtn.configuration updatedConfigurationForButton:self.rightBubbleBtn]; // iOS 17+ 推荐用法（自动生成新 config）
 
        config.attributedTitle = [self bubbleAttributeWithTitle:USUser.user.relUser.sayToRel];
        
        self.rightBubbleBtn.configuration = config;
        
    }else{
        
        self.rightBubbleBtn.hidden = YES;
    }
    
    
    
}
  
- (NSMutableAttributedString *)bubbleAttributeWithTitle:(NSString *)title {
    NSInteger size = 17;
    if (title.length > 12) {
        size = size -  (title.length / 7 - 1);
        if (self.view.jk_height < 800) {
            size = 16 - (title.length / 5);
        }
    }
   
    NSMutableAttributedString *attrTitle = [[NSMutableAttributedString alloc] initWithString: title];
    [attrTitle addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:MIN(17, MAX(11, size))] range:NSMakeRange(0, attrTitle.length)];
    
    return attrTitle;
}

@end
